/**
 * @description: Midway 中间键:请求记录
 * @version: 0.0.1
 * @author: xiech
 * @Date: 2023-05-31 11:33:13
 */

import { Middleware, IMiddleware } from '@midwayjs/core';
import { NextFunction, Context } from '@midwayjs/koa';

@Middleware()
export class ReportMiddleware implements IMiddleware<Context, NextFunction> {
  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // 控制器前执行的逻辑
      const start = new Date().getTime();
      // 执行下一个 Web 中间件，最后执行到控制器
      const result = await next();

      // 请求时长
      const rs = Math.ceil(new Date().getTime() - start);

      ctx.set('X-Response-Time', rs + 'ms');

      const protocol = ctx.protocol.toUpperCase();
      const status = ctx.status;
      const length = ctx.length || '-';
      const referrer = ctx.get('referrer') || '-';
      const ua = ctx.get('user-agent') || '-';
      const serverTime = ctx.response.get('X-Server-Response-Time') || '-';
      // 控制器之后执行的逻辑
      ctx.logger.info(` [ym-Midway:访问日志] ${protocol} ${status} ${length} ${referrer} ${rs} ${serverTime} ${ua} `);
      
      return result;
    };
  }

  static getName(): string {
    return 'report';
  }
}
